#include "Sprite.h"

LPD3DXSPRITE CSprites::_spriteHandler;
//constructor
CSprites::CSprites(LPDIRECT3DTEXTURE9 image, bool loop,int index,int count,int row,int width,int height, int left,int top,int totalExistTime,int interval)
{
	_loop=loop;
	_index=index;
	_count=count;
	_row=row;
	_clear=true;
	_width=width;
	_height=height;
	_alpha=255;
	_image=image;
	_left=left;
	_top=top-_height;
	_rootTime=_oldTime=GetTickCount();
	_totalExistTime=totalExistTime;
	_interval=interval;
	_enable=true;
}

CSprites::CSprites(LPCSTR filePath, int width, int height, int count,int row)
{
	_image=LoadTexture(filePath,0);
	_width=width;
	_height=height;
	_count=count;
	_row=row;
	_index=0;
}
CSprites::~CSprites(void)
{

}

void CSprites::Draw(int topRect, int StyleDraw,bool isClear)
{
	RECT rec;
	rec.left=_index*_width;
	rec.top=_row;
	rec.bottom=rec.top+_height;
	rec.right=rec.left+_width;
	/*if (_image!=NULL)
	{
		if ((DWORD)_interval!=0 && GetTickCount()-_oldTime>=(DWORD)_interval)
		{
			if (!isClear && GetTickCount()-_rootTime <= _totalExistTime)
			{
				_clear=!_clear;//bat tat hieu ung nhap nhay
			}
			else _clear=true;
			if (_enable)
			{
				switch(StyleDraw)
				{
				case -1: //alpha down
					_alpha-=10;
					if (_alpha<0)
					{
						_alpha=0;
					}
					break;
				case 0://draw normal
					if (_loop)
					{
						_index=(_index+1)%_count;
					} 
					else
					{
						_index++;
						if (_index==_count)
						{
							_index=0;
							_enable=false;
						}
					}
					break;
				}
			}
			_oldTime=GetTickCount();
		}*/
		_spriteHandler->Begin(D3DXSPRITE_ALPHABLEND);
		D3DXVECTOR3 position(_left,(float)(_top-topRect),0);
		_spriteHandler->Draw(
			_image,
			&rec,
			NULL,
			&position,
			D3DCOLOR_XRGB(_clear?_alpha:100,255,255));
		_spriteHandler->End();
	//}
}
void CSprites::Render(float X,float Y,int index)
{
	RECT rect;
	rect.left=(index%_row)* _width;
	rect.top=index/_row*_height;

	rect.right=rect.left+_width;
	rect.bottom=rect.top+_height;

	D3DXVECTOR3 position(X,Y,0);
	_spriteHandler->Begin(D3DXSPRITE_ALPHABLEND);
	_spriteHandler->Draw(
		_image,
		&rect,
		NULL,
		&position,
		D3DCOLOR_XRGB(255,255,255));
	_spriteHandler->End();
}
LPDIRECT3DTEXTURE9 CSprites::LoadTexture(LPCSTR filePath,D3DCOLOR transcolor)
{
	LPDIRECT3DTEXTURE9 texture=NULL;
	D3DXIMAGE_INFO info;
	LPDIRECT3DDEVICE9 d3ddv;
	_spriteHandler->GetDevice(&d3ddv);
	HRESULT result=D3DXGetImageInfoFromFileA(filePath,&info);
	if (result!=D3D_OK)
	{
		return NULL;
	}
	result=D3DXCreateTextureFromFileExA(
		d3ddv,
		filePath,
		info.Width,
		info.Height,
		1,
		D3DPOOL_DEFAULT,
		D3DFMT_UNKNOWN,
		D3DPOOL_DEFAULT,
		D3DX_DEFAULT,
		D3DX_DEFAULT,
		transcolor,
		&info,
		NULL,
		&texture);
	if (result!=D3D_OK)
	{
		return NULL;
	}
	return texture;
}